<template>
	<view class="box">
		<!-- 选择会员 -->
		<view class="selectMember">
			<view class="member">
				<text style="position: relative;">{{fillFormDate || '日期：'}}
					<picker mode="date" :start="start" :end="end"  @change="bindDateChange" v-if="!selected" style="position: absolute;left:0;top: 0;width: 100%;height: 100%;">
					</picker> 
				</text>
			</view>
			<view class="save" @click="showModalbtn(4)" v-if="selected != 1 ">保存</view>
			<view class="toSend" @click="selected != 1 ? showModalbtn(2) : ''" >申请评估</view>
		</view>
		<view class="content">
			<view class="question" v-for="(item,index) in psychologyQuestion" :key="index">
				<view class="title">
					<text>{{index < 9 ? '0'+ Number(index+1) : Number(index+1)}}</text>
					<view>{{item.name}}</view>
				</view>
				<view v-if="item.adTopicsRepliesEntityList.length <= 0">
					<view class="entry" v-if="item.name.indexOf('收缩压') > -1">
						<input type="number" :disabled="selected == 1" placeholder="收缩压" class="systolicPressure" v-model="systolic" @blur="systolicInput($event,item)">|
						<input type="number" :disabled="selected == 1" placeholder="舒张压" v-model="diastolic" @blur="diastolicInput($event,item)" class="diastolicPressure">
					</view>
					<view class="entry" v-else>
						<input type="number"  @blur="regular($event,item,name='oneDecimal')" placeholder="体重指数（BMI）" v-model="item.envalue" v-if="item.name.indexOf('体重指数') > -1">
						<input type="number"  @blur="regular($event,item,name='oneDecimal')" placeholder="空腹血糖(GLU)" v-model="item.envalue" v-else-if="item.name.indexOf('空腹血糖') > -1">
						<input type="number"  @blur="regular($event,item,name='oneDecimal')" placeholder="餐后2小时血葡萄糖(2HPG)" v-model="item.envalue" v-else-if="item.name.indexOf('葡萄糖') > -1">		
						<input type="number"  @blur="regular($event,item,name='oneDecimal')" placeholder="高密度脂蛋白（DHL）" v-model="item.envalue" v-else-if="item.name.indexOf('高密度脂蛋白') > -1">
						<input type="number"  @blur="regular($event,item,name='twoDecimal')" placeholder="甘油三酯（TG）" v-model="item.envalue" v-else-if="item.name.indexOf('甘油三酯') > -1">
						<input type="number"  @blur="regular($event,item,name='integer')" placeholder="数值" v-model="item.envalue" v-else>
					</view>
				</view>
				<view v-else>
					<view class="option" v-for="(bitem,bindex) in item.adTopicsRepliesEntityList" :key="bindex">
						<view @click="answer(item,bitem)">
							<text>{{bitem.elections}}、{{bitem.value}}</text> 
							<image src="@/static/img/select@2x.png"  v-if="bitem.checked == false"></image>  
							<image src="@/static/img/selected@2x.png" v-else></image>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {getUrlParam,regular} from '@/static/js/filter.js'
	export default {
		data () {
			const currentDate = this.getDate({
				format: true
			})
			return {
				start:'',
				end:currentDate,
				fillFormDate:'',
				selected:'', //申请评估进来的状态
				psychologyQuestion:{},
				id:'',
				systolic:'',
				diastolic: '',
			}
		},
		created() {
			const _this = this;
			_this.id = getUrlParam('id');
			_this.selected = getUrlParam('selected');
			_this.questionArr().then((response) => {
				if(response) {
					if(_this.id) {
						_this.$api.appDiseaseDangeDetail(_this.id).then((res) => {
							if(res.data.returnCode == 200) {
								const data1 = res.data.result;
								const data2 = res.data.result && res.data.result.userTopicsEntities;
								_this.fillFormDate = data1.fillFormDate;
								_this.userId = data1.userId;
								_this.userHealthId = data1.userHealthId;
								_this.userName = data1.userName;
								_this.userHealthName = data1.userHealthName;
								_this.psychologyQuestion.map((a) => {
									data2.map((b,bi) => {
										if(a.id == b.titleId) {
											a.nid = b.id
											if(b.titleId == 276) {
												_this.systolic = b.userValue.split('/')[0];
												_this.diastolic = b.userValue.split('/')[1]
											}else if(a.adTopicsRepliesEntityList.length <= 0) {
												a.envalue = b.userValue;
											}else {
												a.adTopicsRepliesEntityList.map((c) => {
													c.nid = b.id
													if(c.elections == b.userOption) {
														c.checked = true
													}
												})
											}
										}
									})
								})
							}
						})
					}
					
				}
			})
		},
		methods:{
			regular,
			systolicInput(e,item) {
				var reg = /^[1-9]\d*$/;
				if(!reg.test(e.detail.value)){
					uni.showToast({
						title:'请输入0-300的正整数',
						icon:'none'
					})
					this.systolic =  ''
					return				
				}else{
					if(e.detail.value >= 300 || e.detail.value < 0){
						this.systolic =  ''
						uni.showToast({
							title:'请输入0-300的正整数',
							icon:'none'
						})
						return
					}
				}
			},
			diastolicInput(e,item) {
				var reg = /^[1-9]\d*$/;
				if(!reg.test(e.detail.value)){
					this.diastolic =  ''
					uni.showToast({
						title:'请输入0-300的正整数',
						icon:'none'
					})
					return	
				}else{
					if(e.detail.value >= 300 || e.detail.value < 0){
						this.diastolic =  ''
						uni.showToast({
							title:'请输入0-300的正整数',
							icon:'none'
						})
						return
					}
				}
			},
			showModalbtn(e) {
				const _this = this;
				if(!_this.fillFormDate){
					uni.showToast({
						title:'请选择填写时间',
						icon:'none'
					})
					return
				}
				if(!_this.systolic){
					uni.showToast({
						title:'请输入收缩压',
						icon:'none'
					})
					return
				}
				if(!_this.diastolic){
					uni.showToast({
						title:'请输入舒张压',
						icon:'none'
					})
					return
				}
				var emptyArr = [];
				var hasArr = [];
				this.psychologyQuestion.map((a)=>{
					if(a.adTopicsRepliesEntityList.length <= 0) {
						a.envalue = a.envalue + ''
						if(a.envalue == '' && a.name.indexOf('收缩压') == -1) {
							emptyArr.push(a)
						}else {
							hasArr.push(a)
						}			
					}else if(a.adTopicsRepliesEntityList.length > 0) {
						if(JSON.stringify(a.adTopicsRepliesEntityList).indexOf('true') > -1){
							hasArr.push(a)
						}else{
							emptyArr.push(a)
						}
					}
				})
				if(emptyArr.length > 0){
					if(emptyArr[0].adTopicsRepliesEntityList.length <= 0) {
						uni.showToast({
							title:'请输入'+emptyArr[0].name,
							icon:'none'
						})
						return
					}else {
						uni.showToast({
							title:'请选择'+emptyArr[0].name,
							icon:'none'
						})
						return
					}
					
				}
				
				// 传送给后台的值
				const appUserTopicsEntities = []
				hasArr.map((a) => {
					if(a.name.indexOf('收缩压') > -1) {
						appUserTopicsEntities.push({
							titleId:a.id,
							id:a.nid || '', //编辑时需要
							userOption:'',
							userValue: this.systolic+'/'+this.diastolic,
							type:a.type
						})
					}else {
						if(a.adTopicsRepliesEntityList.length <= 0) {
							appUserTopicsEntities.push({
								titleId:a.id,
								id:a.nid || '', //编辑时需要
								userOption:'',
								userValue: String(a.envalue),
								type:a.type
							})
						}else if(a.adTopicsRepliesEntityList.length > 0){
							const checked = a.adTopicsRepliesEntityList.filter((c)=>{return c.checked})
							appUserTopicsEntities.push({
								titleId:a.id,
								id:checked && checked[0] && checked[0].nid || '', //编辑时需要
								userOption:checked[0].elections,
								userValue: checked[0].value,
								type:a.type
							})
						}
					}
					
				})
				
				const record = {
					appUserTopicsEntities:appUserTopicsEntities,
					appUserTopicsTitleEntity: {
						healthId: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).healthId ||'',
						userId: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).userId || '',
					},
					fillFormDate: _this.fillFormDate,
					status: 4,
					type: 11,
					title: 46,
					source: 1,
					userHealthId: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).healthId ||'',
					userHealthName:localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).healthName ||'',
					userId: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).userId || '',
					userName: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).realName || '',
				}
				if(_this.id) {
					record.id = Number(_this.id);
					record.appUserTopicsTitleEntity.id = _this.editTid
					if(e == 4){
						_this.$api.appDiseaseDangeUpdate(record).then((res) => {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							})
							setTimeout(() => {
								uni.navigateTo({
									url:'/pages/futureDiseases/navigation?current=3'
								})
							},2000)
						})
					}else{
						_this.$api.appDiseaseDangeByStatus(record.id,2).then((res) => {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							})
							setTimeout(() => {
								uni.navigateTo({
									url:'/pages/futureDiseases/navigation?current=3'
								})
							},2000)
						})
					}
					
				}else {
					if(e == 2) {
						_this.$api.appDiseaseDangeAdd(record).then((res) => {
							if(res.data.returnCode == 200) {
								_this.$api.appDiseaseDangeByStatus(res.data.result.id,2).then((res) => {
									uni.showToast({
										title: res.data.message,
										icon: 'none'
									})
									setTimeout(() => {
										uni.navigateTo({
											url:'/pages/futureDiseases/navigation?current=3'
										})
									},2000)
								})
							}
						})
					}else {
						_this.$api.appDiseaseDangeAdd(record).then((res) => {
							if(res.data.returnCode == 200) {
								uni.showToast({
									title: res.data.message,
									icon: 'none'
								})
								setTimeout(() => {
									uni.navigateTo({
										url:'/pages/futureDiseases/navigation?current=3'
									})
								},2000)
							}
						})
					}
					
				}
			},
			answer(item,bitem) {
				if(this.selected == 1) {
					return 
				}
				item.adTopicsRepliesEntityList.map((a) => {
					return a.checked = false
				})
				bitem.checked = true
			},
			questionArr() {
				return new Promise((success,error)=>{
					this.$api.psychologyQuestion('ids=46').then((res)=>{
						if(res){
							const data = res.data.result[46] && res.data.result[46].adTopicsRepliesEntityList.map((b)=>{
								b.envalue = ''
								b.adTopicsRepliesEntityList.map((c)=>{c.checked = false;return b})
								return b
							})
							this.psychologyQuestion = data;
							success(res.data.result)
						}else{
							error('')
						}
					})
				})
			},
			// 日期
			bindDateChange(e) { 
				this.fillFormDate = e.target.value;
			},
			// 获取当前时间
			getDate(type) {
			   const date = new Date();
			   let year = date.getFullYear();
			   let month = date.getMonth() + 1;
			   let day = date.getDate();
			  
			   if (type === 'start') {
				year = year - 60;
			   } else if (type === 'end') {
				year = year + 2;
			   }
			   month = month > 9 ? month : '0' + month;;
			   day = day > 9 ? day : '0' + day;
			   return `${year}-${month}-${day}`;
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/static/css/monitor/accomplishment/index.scss';
	.question {
		.option {
			input {
				background: #FBFBFB;
				border: 1upx solid #E3E3E3;
				border-radius: 12upx;
				height: 60upx;
				width: 100%;
				font-size: 30upx;
				padding: 0 13upx;
				box-sizing: border-box;
			}
		}
	}
	.entry {
		display: flex;
		margin:30upx 0 0 58upx;
		input {
			font-size: 30upx;
			color: #333333;
			width: 100%;
		}
		.systolicPressure {
			width: 148upx;
		}
		.diastolicPressure {
			margin-left: 60upx;
			flex: 1;
		}
	}
</style>
